rm(list=ls())
library(tidyverse)
library(dplyr)
library(data.table)
library(ggplot2)  
library(magrittr)
library(ggpubr)

setwd(dirname(rstudioapi::getActiveDocumentContext()$path))

load('Data/Census/census_plc.RData')
final <- readRDS('Data/Prediction/img5_weighted_opencv_cov2f_nofw_level.rds')

create_df <- function(limit_city, dataf, race){
  df <- dataf %>% drop_na(race.mt, race.ff, race.hybrid, race.s, race.gs, race.lstm_wk) %>% filter(place_fips %in% limit_city)
  
  df$place_fips <- df$state
  df$year <- floor(df$year/10) * 10
  
  df %<>% select(year, place_fips, matches('(mt|s\\.|gs|lstm_wk|fbisg|ff|hybrid)')) 
  lab <- c('True','BSO', 'BISG', 'fBISG', 'LSTM', 'Image', 'Hybrid')
  from<- c('mt', 's', 'gs', 'fbisg', 'lstm_wk', 'ff', 'hybrid')
  df[[paste0('mt.', race)]] <- as.numeric(df$race.mt == race)
  temp <- df %>% group_by(year, place_fips) %>% summarize_at(vars(matches(paste0('\\.', race, '$'))), ~ mean(.x, na.rm=T)) %>%
    gather(key, value, -year, -place_fips)
  for (i in 1:length(lab)){
    temp$key <- ifelse(temp$key==paste0(from[i], '.', race), lab[i], temp$key)
  }
  temp$key <- factor(temp$key, levels = lab)
  return(temp)
}

# Figure 3
d_bla <- create_df(unique(na.omit(final$place_fips)), final, 'bla')
d_asi <- create_df(unique(na.omit(final$place_fips)), final, 'asi')
d_his <- create_df(unique(na.omit(final$place_fips)), final, 'his')

pdf <- d_asi %>% mutate(l = 'Asian') %>%
  bind_rows(d_bla %>% mutate(l = 'Black')) %>%
  bind_rows(d_his %>% mutate(l = 'Hispanic'))

theme_p <-  theme(legend.position = "bottom",
                  legend.title = element_blank(),
                  legend.text = element_text(size = 8),
                  legend.key=element_blank(),
                  legend.key.size = grid::unit(1.7, "lines"),
                  legend.background = element_rect(fill = "white", colour = "black", size = 0.2),
                  panel.grid.major = element_blank(),
                  panel.grid.minor = element_blank(),
                  axis.text.x = element_text(angle=45, hjust=1, size = 9),
                  axis.title = element_text(size = 9),
                  plot.title = element_text(size=8, hjust = 0.5),
                  strip.text.x = element_text(size = 8))


p <- ggplot(data = pdf, aes(x = year, y = value, color = key, linetype = key)) + 
        geom_smooth(alpha = 0.2, method = 'loess', size = 0.7) +
        labs(x = '', y = '% Minority Elected Officials') +
        facet_wrap(vars(l), scale = 'free', nrow = 1) +
        scale_linetype_manual(name='', values = c('solid', 'longdash', 'dashed', 'dotdash', 'twodash', 'dotted', 'solid')) +
        scale_color_manual(name='', values = c('blue', '#38761d', '#55b32c', '#234912', 'gray45', 'gray70', 'red')) +
        theme_bw() + theme_p + 
        guides(colour = guide_legend(nrow = 1),
               linetype = guide_legend(nrow = 1))

ggsave('Figures/Figure 3.png', p, height = 3.35, width = 7, dpi = 600)


